# coding=utf-8


from rest_framework.routers import DefaultRouter


class Router(DefaultRouter):
    include_root_view = False


class DBRouter(object):
    """
    数据库读写分离
    """

    def db_for_read(self, model, **hints):
        """
        Reads go to a randomly-chosen replica.
        """
        return "read_only"

    def db_for_write(self, model, **hints):
        """
        Writes always go to primary.
        """
        return 'default'

    def allow_migrate(self, db, app_label, model=None, **hints):
        """
        All non-auth models end up in this pool.
        """
        return db == 'default'

    def allow_relation(self, obj1, obj2, **hints):
        db_list = ('default', 'read_only')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None
